package org.cc.media.player;


import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.cc.media.vo.shoutcast.ShoutcastStation;

public class GuiPlayer extends JFrame implements ActionListener, ListSelectionListener {
	
	private static final long serialVersionUID = 1419891650474939513L;
	
	public static final String API_KEY = "sh19qvGfsOJkQ0pv";
	
	private static ShoutcastApiClient api = new ShoutcastApiClient();

	private static ShoutcastStreamPlayer player;
	
	private static ShoutcastMetadataPoller poller;
	
	private static ShoutcastPlaylistDigester digester;
	
	private static InputStream stream;
	
	private static String url;
	
	private static JLabel trackTitle = new JLabel("");
	
	private static JLabel albumArt = new JLabel();
	
	private static JButton buyLink = new JButton();
	
	private static ExecutorService threadExecutor = Executors.newFixedThreadPool(2);;
	
	private static List<ShoutcastStation> stations = new ArrayList<ShoutcastStation>();
	
	public static final void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		GuiPlayer player = new GuiPlayer();
		player.setSize(800, 600);
		player.setLocation(400, 300);
		player.init();
		player.setVisible(true);
		player.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private void init() throws IOException  {
		digester = new ShoutcastPlaylistDigester();
		//stream = digester.getStreamFromUrl(url);
	    this.getContentPane().setLayout(new FlowLayout());

		this.add(trackTitle);
		
		JButton playButton = new JButton("Play!");
		playButton.addActionListener(this);
		this.add(playButton);
		
		JButton stopButton = new JButton("Stop!");
		stopButton.addActionListener(this);
		this.add(stopButton);
		
		stations.addAll(api.getStations("alternative"));
		JList<Object> list = new JList<Object>((Object[]) stations.toArray()); //data has type Object[]
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.setLayoutOrientation(JList.VERTICAL);
		list.setVisibleRowCount(-1);
		list.addListSelectionListener(this);

		JScrollPane listScroller = new JScrollPane(list);
		listScroller.setPreferredSize(new Dimension(250, 80));

		JTabbedPane tabbed = new JTabbedPane();
		tabbed.setName("Genres");
		tabbed.addTab("Alternative", listScroller);
		this.add(tabbed);
		
		BufferedImage myPicture = ImageIO.read(this.getClass().getResource("/desert.jpg"));
		Image scaled = myPicture.getScaledInstance(200, -1, Image.SCALE_SMOOTH);
		albumArt.setIcon(new ImageIcon(scaled));
		this.add(albumArt);
		
		buyLink.addActionListener(this);
		this.add(buyLink);
		

	}

	@Override
	public void actionPerformed(ActionEvent event) {
        String action = event.getActionCommand();
        System.out.println("Command: " + action);
        if (action.equals("Play!")) {
            System.out.println("Play Button pressed!");
            startPlayer();
        }
        else if (action.equals("Stop!")) {
            System.out.println("Stop Button pressed!");
            stopPlayer();
        }
        else if (action.equals("Buy this item!")) {
        	try {
        		System.out.println("New Customer!");
        		JButton button = (JButton) event.getSource();
				openWebpage(new URL(button.getName()));
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
        }
    }

	@Override
	public void valueChanged(ListSelectionEvent event) {
		stopPlayer();
		ShoutcastStation station = (ShoutcastStation) stations.get(event.getLastIndex());
		//stream = digester.getStreamFromId(station.getId());
		url = digester.getUrlFromId(station.getId());
		stream = digester.getStreamFromUrl(url);
		startPlayer();
		
	}

	private void startPlayer() {
		if (player != null && player.getPlayStream()) {
			// do nothing
		} else if (player != null) {
			player.setPlayStream(false);
			player = new ShoutcastStreamPlayer(stream);
			threadExecutor.submit(player);
		} else {
			player = new ShoutcastStreamPlayer(stream);
			threadExecutor.submit(player);
		}
		if (poller != null && poller.getPollMeta()) {
			// do nothing
		} else if (poller != null) {
			poller.setPollMeta(false);
			poller = new ShoutcastMetadataPoller(url);
			threadExecutor.submit(poller);
		} else {
			poller = new ShoutcastMetadataPoller(url);
			threadExecutor.submit(poller);			
		}

	}
	
	private void stopPlayer() {
		trackTitle.setText("");
		if (poller != null) {
			poller.setPollMeta(false);
		}
		if (player != null) {
			player.setPlayStream(false);
		}
	}
	
	public static void openWebpage(URI uri) {
	    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
	    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
	        try {
	            desktop.browse(uri);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	}

	public static void openWebpage(URL url) {
	    try {
	        openWebpage(url.toURI());
	    } catch (URISyntaxException e) {
	        e.printStackTrace();
	    }
	}
	
	public static JLabel getTrackTitle() {
		return trackTitle;
	}

	public static void setTrackTitle(JLabel trackTitle) {
		GuiPlayer.trackTitle = trackTitle;
	}

	public static JLabel getAlbumArt() {
		return albumArt;
	}

	public static void setAlbumArt(JLabel albumArt) {
		GuiPlayer.albumArt = albumArt;
	}

	public static JButton getBuyLink() {
		return buyLink;
	}

	public static void setBuyLink(JButton buyLink) {
		GuiPlayer.buyLink = buyLink;
	}
	
public class StationListItem {
	private String stationName;
	private String stationUrl;
	
	public StationListItem(String stationName, String stationUrl) {
		this.stationName = stationName;
		this.stationUrl = stationUrl;
	}
	
	public String getStationName() {
		return stationName;
	}
	public void setStationName(String stationName) {
		this.stationName = stationName;
	}
	public String getStationUrl() {
		return stationUrl;
	}
	public void setStationUrl(String stationUrl) {
		this.stationUrl = stationUrl;
	}
	
	@Override
	public String toString() {
		return stationName;
	}
	
}

}
